package com.yiwei.zhh.activity;

import android.annotation.TargetApi;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.allen.library.SuperButton;
import com.yiwei.zhh.R;
import com.yiwei.zhh.api.Api;
import com.yiwei.zhh.api.bean.BankCardAuthBean;
import com.yiwei.zhh.api.bean.BankCardAuthMoreBean;
import com.yiwei.zhh.api.bean.BankCardDetailBean;
import com.yiwei.zhh.api.bean.BankcardSendCode;
import com.yiwei.zhh.constant.Const;
import com.yiwei.zhh.constant.UserGlobal;
import com.yiwei.zhh.event.OnBindBankSuccess;
import com.yiwei.zhh.model.BankCardDetailModel;
import com.yiwei.zhh.util.Network;
import com.yiwei.zhh.util.RxLifeUtil;
import com.yiwei.zhh.util.ToastUtil;
import com.yiwei.zhh.util.UI;
import com.yiwei.zhh.util.Util;
import com.yiwei.zhh.view.Dialog;
import com.yiwei.zhh.view.V19FrameLayout;

import org.greenrobot.eventbus.EventBus;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by Administrator on 2018/6/10.
 */
//微米
public class BankIdentityActivity extends BaseActivity {

    @BindView(R.id.btn_back)
    ImageView btnBack;
    @BindView(R.id.txt_title)
    TextView txtTitle;
    @BindView(R.id.txt_right)
    TextView txtRight;
    @BindView(R.id.layout_title)
    V19FrameLayout layoutTitle;
    @BindView(R.id.edit_name)
    EditText editName;
    @BindView(R.id.btn_name)
    ImageView btnName;
    @BindView(R.id.edit_num)
    EditText editNum;
    @BindView(R.id.edit_phone)
    EditText editPhone;
    @BindView(R.id.btn_phone)
    ImageView btnPhone;
    @BindView(R.id.edit_send_code)
    EditText editSendCode;
    @BindView(R.id.btn_send_code)
    TextView btnSendCode;
    @BindView(R.id.layout_send_code)
    LinearLayout layoutSendCode;
    @BindView(R.id.btn_submit)
    SuperButton btnSubmit;
    @BindView(R.id.img_agree)
    ImageView imgAgree;
    @BindView(R.id.txt_agree)
    TextView txtAgree;
    @BindView(R.id.btn_check_bank)
    TextView btnCheckBank;
    private Unbinder unbinder;
    private boolean isCheckAgree = true;
    private String SignCode;
    private String is_sign;
    private String dk_type;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bank_identity);
        initBar();
        unbinder = ButterKnife.bind(this);
        init();
    }

    private void init() {
        txtTitle.setText("银行卡认证");
        txtRight.setText("联系客服");
        txtRight.setVisibility(View.VISIBLE);
        Util.bankCardNumAddSpace(editNum);
        editName.setText(UserGlobal.getRealName());

        String bank_id = getIntent().getStringExtra("bank_id");
        if (!TextUtils.isEmpty(bank_id)) {
            getBankInfo(bank_id);
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (timer != null) timer.cancel();
        unbinder.unbind();
        unbinder = null;
    }


    private static final int TIME = 60 * 1000;  //验证码倒计时时间
    private CountDownTimer timer = new CountDownTimer(TIME, 1000) {

        @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
        @Override
        public void onTick(long millisUntilFinished) {
            try {
                btnSendCode.setEnabled(false);
                btnSendCode.setText((millisUntilFinished / 1000) + getResources().getString(R.string.resend));
                btnSendCode.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.gray));
            } catch (Resources.NotFoundException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onFinish() {
            resetBtn();
        }
    };
    private boolean isSend;


    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private void resetBtn() {
        if (timer != null) timer.cancel();
        btnSendCode.setEnabled(true);
        if (isSend)
            btnSendCode.setText(getResources().getString(R.string.send_code_again));
        else
            btnSendCode.setText(getResources().getString(R.string.get_code));
        btnSendCode.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.blue));
    }


    private void getBankcardAuthMore(String bankcard, String mobile, String verify_code) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.makeText(this, "网络连接失败").show();
            return;
        }
        loadingDialog.show();
        BankCardAuthMoreBean bean = new BankCardAuthMoreBean();
        bean.bankcard = bankcard;
        bean.mobile = mobile;
        bean.verify_code = verify_code;
        bean.sign_code = SignCode;
        bean.dk_type = dk_type;
        bean.is_sign = is_sign;
        Api.api_service.getBankcardAuthMore(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    EventBus.getDefault().post(new OnBindBankSuccess());
                    ToastUtil.makeText(getApplicationContext(), "银行卡认证成功", Toast.LENGTH_SHORT).show();
                    finish();
                });
    }

    private void getBankInfo(String id) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.makeText(this, "网络连接失败").show();
            return;
        }
        loadingDialog.show();
        BankCardDetailBean bean = new BankCardDetailBean();
        bean.bankcard_id = id;

        Api.api_service.getBankcardDetail(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    BankCardDetailModel.DataBean item = result.data;
                    editName.setText(item.real_name);
                    editPhone.setText(item.mobile);
                    editNum.setText(item.bankcard);
                });
    }

    private void getBankCardSendCode(String bankcard, String mobile) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.makeText(this, "网络连接失败").show();
            return;
        }
        loadingDialog.show();
        BankcardSendCode bean = new BankcardSendCode();
        bean.bankcard = bankcard;
        bean.mobile = mobile;

        Api.api_service.getBankcardSendCode(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    isSend = true;
                    timer.start();
                    SignCode = result.data.sign_code;
                    is_sign = result.data.is_sign;
                    dk_type = result.data.dk_type;
                    ToastUtil.makeText(getApplicationContext(), "验证码已发送", Toast.LENGTH_SHORT).show();

                });
    }

    private boolean checkInput() {
        if (TextUtils.isEmpty(editNum.getText().toString().trim())) {
            ToastUtil.makeText(getApplicationContext(), getResources().getString(R.string.bank_id_is_empty), Toast.LENGTH_SHORT).show();
            return false;
        }
        if (TextUtils.isEmpty(editPhone.getText().toString().trim())) {
            ToastUtil.makeText(getApplicationContext(), getResources().getString(R.string.phone_is_empty), Toast.LENGTH_SHORT).show();
            return false;
        }

        return true;
    }

    private boolean checkCode() {
        if (TextUtils.isEmpty(editSendCode.getText().toString().trim())) {
            ToastUtil.makeText(getApplicationContext(), getResources().getString(R.string.code_is_empty), Toast.LENGTH_SHORT).show();
            return false;
        }
        if (!isCheckAgree) {
            ToastUtil.makeText(getApplicationContext(), "请勾选同意协议");
            return false;
        }
        return true;
    }


    @OnClick({R.id.txt_right, R.id.img_agree, R.id.txt_agree, R.id.btn_check_bank, R.id.btn_back, R.id.btn_name, R.id.btn_phone, R.id.btn_send_code, R.id.btn_submit})
    public void onViewClicked(View view) {
        if (UI.isFastClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.txt_right:
                Util.startActivity(this,WechatChatActivity.class);
                break;
            case R.id.img_agree:
                isCheckAgree = !isCheckAgree;
                if (isCheckAgree) {
                    imgAgree.setImageResource(R.mipmap.img_pay_cb_open);
                } else {
                    imgAgree.setImageResource(R.mipmap.img_pay_cb_close);
                }

                break;
            case R.id.txt_agree:

                Intent intent = new Intent(this, AboutActivity.class);
                intent.putExtra("id", Const.ContractType.WEITUO);
                intent.putExtra("type", 2);
                startActivity(intent);
                overridePendingTransition(R.anim.right_enter, R.anim.left_out);
                break;
            case R.id.btn_check_bank:
                Util.startActivity(this, BankSupportActivity.class);
                break;
            case R.id.btn_back:
                finish();

                break;
            case R.id.btn_name:
                showDialog(getResources().getString(R.string.bank_dialog_title1), getResources().getString(R.string.bank_dialog_content1));

                break;
            case R.id.btn_phone:
                showDialog(getResources().getString(R.string.bank_dialog_title1), getResources().getString(R.string.bank_dialog_content2));

                break;
            case R.id.btn_send_code:
                if (checkInput()) {

                    getBankCardSendCode(editNum.getText().toString().trim().replace(" ", ""), editPhone.getText().toString().trim());
                }
                break;
            case R.id.btn_submit:
                if (checkInput() && checkCode()) {
                    getBankcardAuthMore(editNum.getText().toString().trim().replace(" ", ""), editPhone.getText().toString().trim(), editSendCode.getText().toString().trim());
                }
                break;
        }
    }

    private void showDialog(String title, String content) {
        Dialog.showDefaultDialog(this, title, content, "", getResources().getString(R.string.ok), false, new Dialog.DialogDefaultClickListener() {
            @Override
            public void confirm() {

            }

            @Override
            public void cancel() {

            }
        });
    }
}
